package com.yixun.qfbao.util;

import com.yixun.qfbao.api.service.impl.WeiXinServiceImpl;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class SSLClient {
    private static Logger logger = LoggerFactory.getLogger(WeiXinServiceImpl.class);

    public static final int http_ok = 200;// 返回状态码正常

    public static final int CONNECTION_TIMEOUT = 5000;// 连接超时

    public static final int READDATA_TIMEOUT = 10000;// 数据读取等待超时

    public static final int DEFAULT_HTTP_PORT = 80;// http端口

    public static final int DEFAULT_HTTPS_PORT = 443;// https端口


    public static String postSSLUrlWithParams(String url, Map<String, String> reqMap, String encoding) {
        logger.info("httpsClient访问开始...");
        CloseableHttpClient httpClient = createSSLClientDefault();
        HttpPost post = new HttpPost(url);
        // 添加参数
        List<NameValuePair> params = new ArrayList<>();
        if (reqMap != null && reqMap.keySet().size() > 0) {
            Iterator<Map.Entry<String, String>> iter = reqMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<String, String> entity = iter.next();
                params.add(new BasicNameValuePair(entity.getKey(), entity.getValue()));
            }
        }
        StringBuilder sb = new StringBuilder();
        BufferedReader br = null;
        try {
            // 设置客户端请求的头参数getParams已经过时,现在用requestConfig对象替换
            // httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,CONNECTION_TIMEOUT);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT)
                    .setSocketTimeout(READDATA_TIMEOUT).build();
            post.setConfig(requestConfig);
            // 设置编码格式
            post.setEntity(new UrlEncodedFormEntity(params, encoding));
            HttpResponse response = httpClient.execute(post);
            HttpEntity httpEntity = response.getEntity();
            br = new BufferedReader(new InputStreamReader(httpEntity.getContent(),encoding));
            String s = null;
            while((s=br.readLine())!=null){
                sb.append(s);
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("编码格式输入错误: {}", e);
            throw new RuntimeException("指定的编码集不对,您目前指定的编码集是:" + encoding);
        } catch (ClientProtocolException e) {
            logger.error("postSSLUrlWithParams error: {}", e);
        } catch (IOException e) {
            logger.error("读取流文件异常: {}", e);
            throw new RuntimeException("读取流文件异常", e);
        }catch (Exception e) {
            logger.error("通讯未知系统异常: {}", e);
            throw new RuntimeException("通讯未知系统异常",e);
        }finally{
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    logger.error("关闭br异常: {}", e);
                }
            }
        }
        return sb.toString();
    }

    public static CloseableHttpClient createSSLClientDefault(){
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                //信任所有
                public boolean isTrusted(X509Certificate[] chain,
                                         String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            logger.error("createSSLClientDefault error: {}", e);
        } catch (NoSuchAlgorithmException e) {
            logger.error("createSSLClientDefault error: {}", e);
        } catch (KeyStoreException e) {
            logger.error("createSSLClientDefault error: {}", e);
        }
        return  HttpClients.createDefault();
    }

    public static void main(String[] args) {
        String s = postSSLUrlWithParams("https://api.apiopen.top/singlePoetry",null,"UTF-8");
        System.out.println(s);

    }
}
